
#include <ESP8266WebServer.h>
#include <uri/UriBraces.h>
#include <uri/UriRegex.h>

ESP8266WebServer server(80);

void _setupServer(){
  
  server.on(UriBraces("/digital/read/{}/{}"), []() {     
    int pin = server.pathArg(0).toInt(); 
    int v = digitalRead(pin);
    server.send(200, "text/plain", "/digital/read: " + v );
  });
  
  server.on(UriBraces("/digital/write/{}/{}"), []() {     
    int pin = server.pathArg(0).toInt();
    String m = server.pathArg(1); 
    digitalWrite(pin, m == "1" ? HIGH : LOW);
    server.send(200, "text/plain", "/digital/write: " + pin );
  });
  
  server.on(UriBraces("/analog/write/{}/{}"), []() {     
    int pin = server.pathArg(0).toInt();
    int m = server.pathArg(1).toInt(); 
    analogWrite(pin, m);
    server.send(200, "text/plain", "set mode on: " + pin );
  });
  
  server.on(UriBraces("/mode/{}/{}"), []() {     
    int pin = server.pathArg(0).toInt();
    String m = server.pathArg(1);
    pinMode(pin, m == "i" ? INPUT : OUTPUT);
    digitalWrite(pin, HIGH);
    server.send(200, "text/plain", "set mode on: " + pin );
  });

  server.on(UriBraces("/analog/read/{}"), []() {
    
    _info("GET /analogRead/{pin}");
    
    String p = server.pathArg(0);
    
    int pin = p.toInt();
    uint16_t v = analogRead(pin); 
    
    server.send(200, "text/plain", String(v) );
    
  });  
}

void startServer(){
  _setupServer();
  server.begin();
  Serial.println("HTTP server started"); 
}